package com.habdqn.studentmanager.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.habdqn.studentmanager.util.ProjectUtil;

/**
 * @author Administrator 登陆拦截 2017年5月15日
 * 
 */
public class ProjectInterceptor implements HandlerInterceptor {
	
	private static final Logger logger = LoggerFactory.getLogger(ProjectInterceptor.class);
	
	private ThreadLocal<Long> times = new ThreadLocal<>();
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
	        throws Exception {
		
		ProjectUtil.setRequests(request);
		ProjectUtil.setResponses(response);
		ProjectUtil.setServletContext(request.getServletContext());
		
		times.set(System.currentTimeMillis());
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
	        ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
	        throws Exception {
		
		ProjectUtil.remove();
		
		// 记录处理时间
		Long time = System.currentTimeMillis();
		String url = request.getServletPath();
		logger.debug("Cost {} ms to {}", time - times.get(), url);
		times.remove();
	}

}
